package api

import (
	"cron_table_admin/internal/dao"
	"cron_table_admin/internal/model"
	"cron_table_admin/internal/request"
	"cron_table_admin/internal/response"
	"time"

	"github.com/gin-gonic/gin"
)

func CreateCorn(c *gin.Context) error {
	var req request.CreateCronReq
	err := c.ShouldBindBodyWithJSON(&req)
	if err != nil {
		response.FailWithMessage("参数异常", c)
		return err
	}
	cronModel := &model.Cron{
		Name:           req.CronName,
		ReqType:        req.CronReqType,
		Classification: req.Classification,
		Expr:           req.CronExpr,
		Desc:           req.CronDesc,
		Url:            req.CronUrl,
		Param:          req.CronParam,
		Method:         req.CronMethod,
		Status:         0,
		CreatedAt:      time.Now(),
		UpdatedAt:      time.Now(),
	}
	err = dao.NewCronDao().Create(c, cronModel)
	if err != nil {
		response.FailWithMessage("数据操作失败", c)
		return err
	}
	response.OkWithData("create task success", c)
	return nil
}

func UpdateCorn(c *gin.Context) error {
	var req request.UpdateCronReq
	err := c.ShouldBindBodyWithJSON(&req)
	if err != nil {
		response.FailWithMessage("参数异常", c)
		return err
	}
	cronInfo, err := dao.NewCronDao().GetDetailById(c, int64(req.CronId))

	if err != nil {
		response.FailWithMessage("数据库异常", c)
		return err
	}

	if cronInfo == nil {
		response.FailWithMessage("数据不存在", c)
		return err
	}

	updateData := map[string]any{
		"name":       req.CronName,
		"type":       req.CronReqType,
		"expr":       req.CronExpr,
		"desc":       req.CronDesc,
		"url":        req.CronUrl,
		"param":      req.CronParam,
		"method":     req.CronMethod,
		"updated_at": time.Now(),
	}

	conditions := []map[string]any{
		{"id": req.CronId},
	}
	_, err = dao.NewCronDao().Update(c, updateData, conditions)
	if err != nil {
		response.FailWithMessage("系统异常", c)
		return err
	}
	_, err = dao.NewCronDao().Update(c, updateData, conditions)

	response.OkWithData("update task success", c)
	return nil
}

func StartOrStopCron(c *gin.Context) error {
	var req request.StartOrStopCronReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage("参数异常", c)
		return err
	}
	//加锁防止重复点击
	cronInfo, err := dao.NewCronDao().GetDetailById(c, int64(req.CronId))
	if err != nil {
		response.FailWithMessage("系统异常", c)
		return err
	}
	if cronInfo == nil {
		response.FailWithMessage("数据不存在", c)
		return err
	}

	if cronInfo.Status == req.OptType {
		response.FailWithMessage("状态操作异常", c)
		return nil
	}

	if req.OptType == 1 {
		//开启任务
		cronInfo.Start()
	} else {
		//关闭任务
		cronInfo.Stop()
	}

	updateData := map[string]any{
		"status": req.OptType,
	}
	conditions := []map[string]any{
		{"id": req.CronId},
	}
	_, err = dao.NewCronDao().Update(c, updateData, conditions)
	response.OkWithData("option task status success", c)
	return nil
}

func ExecuteOnceCron(c *gin.Context) error {
	var req request.ExecuteOnceCronReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage("参数异常", c)
		return err
	}
	cronInfo, err := dao.NewCronDao().GetDetailById(c, int64(req.CronId))
	if err != nil {
		response.FailWithMessage("系统异常", c)
		return err
	}
	if cronInfo == nil {
		response.FailWithMessage("数据不存在", c)
		return nil
	}
	cronInfo.Execute()
	response.OkWithData("task execute once success", c)
	return nil
}

func QueryCron(c *gin.Context) error {
	var req request.QueryCronReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage("参数异常", c)
		return err
	}
	var conditions []map[string]any

	condition := map[string]any{}
	if req.CronId > 0 {
		condition["id"] = req.CronId
	}
	if req.CronName != "" {
		condition["name"] = req.CronName
	}

	if len(condition) > 0 {
		conditions = append(conditions, condition)
	}

	list, err := dao.NewCronDao().Query(c, conditions, req.Page, req.PageSize)
	if err != nil {
		response.FailWithMessage("数据操作异常", c)
		return err
	}
	if len(list) == 0 {
		list = []*model.Cron{}
	}
	total, err := dao.NewCronDao().Count(c, conditions)
	if err != nil {
		response.FailWithMessage("数据操作异常", c)
		return err
	}
	response.OkWithData(response.CronListResp{
		List:     list,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, c)
	return nil
}

func GetCronDetail(c *gin.Context) error {
	var req request.GetCronDetailReq
	err := c.ShouldBindQuery(&req)
	if err != nil {
		response.FailWithMessage("参数异常", c)
		return err
	}
	//参数校验
	if req.CronId <= 0 {
		response.FailWithMessage("参数异常", c)
		return nil
	}
	cronInfo, err := dao.NewCronDao().GetDetailById(c, int64(req.CronId))
	if err != nil {
		response.FailWithMessage("数据操作异常", c)
		return err
	}

	if cronInfo == nil {
		response.FailWithMessage("数据不存在", c)
		return nil
	}
	response.OkWithData(cronInfo, c)
	return nil
}
